package com.socket.nio.nio.future;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author Hexudong
 * @date 2025/4/12
 */
@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap().group(group).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new StringDecoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8082));

        Channel channel = channelFuture.channel();
        log.debug("线程： [{}], channel = [{}]", Thread.currentThread().getName(), channel);

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if ("q".equals(line)) {
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        }, "input").start();

        // closeFuture 1）同步处理 2）异步处理
        ChannelFuture closeFuture = channel.closeFuture();

        /* 方式一：同步处理 */
        //syncHandler(closeFuture);

        /* 方式二：异步处理 */
        asyncHandler(closeFuture, group);
    }

    private static void syncHandler(ChannelFuture closeFuture) throws InterruptedException {
        System.out.println("waiting close...");
        closeFuture.sync();
        log.debug("线程： [{}], 处理关闭之后操作", Thread.currentThread().getName());
    }

    private static void asyncHandler(ChannelFuture closeFuture, NioEventLoopGroup group) {
        closeFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            log.debug("线程： [{}], 处理关闭之后操作", Thread.currentThread().getName());
            group.shutdownGracefully();
        });
    }
}
